import ListEmptyNone from '@/components/antd-comp/empty/emptyNone'
// import { showMessage } from '@/components/antd-comp/message'
import TableGrid from '@/components/antd-comp/table'
import { columnsProps } from '@/components/antd-comp/table/constants'
import ThemeBtn from '@/components/antd-comp/theme-btn'
import FouterPage from '@/components/fouter-page'
import InputAntDef from '@/components/input/InputAntDef'
import { Func } from '@/permissions/constants'
import { useDictStore } from '@/store/dictStore'
import { useFuncsStore } from '@/store/funcStore'
import { useRouteStoreHook } from '@/store/routeStore'
import { useBuriedEvent } from '@/util/buried'
import { fileSizeFormat } from '@/util/utils'
import { ExclamationCircleFilled } from '@ant-design/icons'
import { Button, Dropdown, MenuProps, Modal, Tooltip } from 'antd'
import { ArrowLeft, RotateCw, X } from 'lucide-react'
import { useContext, useEffect, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { Link, useNavigate, useParams } from 'react-router-dom'
import ShadTooltip from '../../components/ShadTooltipComponent'
import { locationContext } from '../../contexts/locationContext'
import { autoTags, deleteFile, readFileByLibDatabase, retryKnowledgeFileApi, setTaglabels } from '../../controllers/API'
import { captureAndAlertRequestErrorHoc } from '../../controllers/request'
import UploadModal from '../../modals/UploadModal'
import { useTable } from '../../util/hook'
import PreviewPage from './components/preview'
import { FileInfoType } from './constants'
import './css/filelib.less'
import './css/index.css'
import InfoHead from './infoHead'
import TagDialog from './tagDialog'
const { confirm } = Modal

// table的唯一id
const getUniqueKey = (record: any) => record.id

export default function FilesPage() {
  /**
   * 功能权限限制
   */
  const { hasFuncPermission } = useFuncsStore()
  const { t } = useTranslation()

  const routeNames = [t('menu.knowledge'), t('lib.details')]
  useRouteStoreHook(routeNames)

  const [tagShow, setTagShow] = useState(false)

  const navigate = useNavigate()

  const { id } = useParams()
  // 上传 上传成功添加到列表
  const [open, setOpen] = useState(false)
  const [title, setTitle] = useState('')

  const { fileLibBuriedEvent } = useBuriedEvent()

  const {
    page,
    pageSize,
    data: datalist,
    total,
    loading,
    setPage,
    search,
    reload,
    filterData,
    refreshData
  } = useTable(
    {},
    param =>
      readFileByLibDatabase({ ...param, id, name: param.keyword }).then((res: any) => {
        if (res) {
          setTitle(res.name)
          updateHeadInfo(res)
          loadTypeList('category', res)
        }
        return res
      }),
    true,
    () => hasFuncPermission([Func.knowledge.fileList])
  )

  const { loadDictOptions } = useDictStore()
  const typeMap = useRef({})
  const loadTypeList = (type = 'category', record) => {
    // loadDictOptions(type).then(res => {
    //   if (res) {
    //     const typeInfo = {}
    //     res.forEach(type => {
    //       typeInfo[type.id] = type.label
    //     })

    //     typeMap.current = typeInfo
    //     updateHeadInfo(record)
    //   }
    // })
    
  }
  useEffect(() => {
    const typeInfo = {}
    typeInfo[-1] = '企业知识库'
    typeInfo[1] = '个人知识库'
    typeMap.current = typeInfo
  }, [])
  
  const handleTypeInfo = val => {
    return typeMap.current[val] || '--'
  }
  const updateHeadInfo = record => {
    setInfo({
      ...info,
      list: [
        {
          name: '类型',
          desc: handleTypeInfo(record.catetory)
        },
        {
          name: '文件数',
          desc: record.total
        },
        {
          name: '模型',
          desc: record.model
        },
        {
          name: '创建用户',
          desc: record.user_name
        },
        {
          name: '创建时间',
          desc: record.create_time?.replace('T', ' ')
        },
        {
          name: '更新时间',
          desc: record.update_time?.replace('T', ' ')
        }
      ],
      case: record.description
    })
  }

  const [isPolling, setIsPolling] = useState(false)
  /**
   * 存在解析中状态时对数据进行轮询，30s一次
   */
  useEffect(() => {
    let pollingTimer = null
    if (datalist.some((item: any) => item.status === 1)) {
      pollingTimer = setTimeout(() => {
        setIsPolling(true)
        reload()
      }, 30 * 1000)
    }
    // 清理函数
    return () => {
      setIsPolling(false)
      if (pollingTimer) {
        clearTimeout(pollingTimer)
      }
    }
  }, [datalist])

  // const [hasPermission, setHasPermission] = useState(true)
  const { appConfig } = useContext(locationContext)

  // filter
  const [filter, setFilter] = useState(0)
  useEffect(() => {
    filterData({ status: filter })
  }, [filter])

  const handleOpen = e => {
    setOpen(e)
    // reload()
  }

  const handleDelete = fileId => {
    fileLibBuriedEvent({
      page: '文件列表页面',
      event_name: '【删除】按钮',
      data_id: id
    })
    if (!hasFuncPermission([Func.knowledge.fileDel])) {
      return
    }
    confirm({
      title: t('prompt'),
      icon: <ExclamationCircleFilled style={{ color: 'red' }} />,
      content: t('lib.confirmDeleteFile'),
      okText: t('delete'),
      okType: 'danger',
      cancelText: t('cancel'),
      autoFocusButton: null,
      centered: true,
      destroyOnClose: true,
      onOk() {
        captureAndAlertRequestErrorHoc(
          deleteFile(fileId).then(res => {
            fileLibBuriedEvent({
              page: '文件列表页面',
              event_name: '确定【删除】按钮',
              data_id: id,
              detail: JSON.stringify({ 结果: res ? '失败' : '成功' })
            })
            reload()
          })
        )
      }
    })
  }

  const [repeatFiles, setRepeatFiles] = useState([])
  const [errorFiles, setErrorFiles] = useState([])

  // 上传结果展示
  const handleUploadResult = (_fileCount, _failFiles, res) => {
    if (res) {
      const _repeatFiles = res.filter(e => e.status === 3)
      const _errorFiles = res.filter(e => e.status === 4)
      console.log('_repeatFiles, _errorFiles', _repeatFiles, _errorFiles)

      if (_errorFiles.length) {
        setErrorFiles(_errorFiles)
      }

      if (_repeatFiles.length) {
        setRepeatFiles(_repeatFiles)
        return
      }
      reload()
    }
  }

  // 重试解析
  const [retryLoad, setRetryLoad] = useState(false)
  const handleRetry = objs => {
    setRetryLoad(true)
    captureAndAlertRequestErrorHoc(
      retryKnowledgeFileApi(objs).then(res => {
        // 乐观更新
        // refreshData(
        //     (item) => ids.includes(item.id),
        //     { status: 1 }
        // )
        reload()
        setRepeatFiles([])
        setRetryLoad(false)
      })
    )
  }

  const selectChange = id => {
    typeSelected.current = id
    setFilter(Number(id))
  }

  const linkToDetail = data => {
    if (data.status === 2) {
      fileLibBuriedEvent({
        page: '文件列表页面',
        event_name: '【详情】按钮',
        data_id: id
      })
      navigate(
        `/filelib/${data.knowledge_id}/${data.id}?knowledge_id=${data.knowledge_id}&file_name=${
          data.file_name
        }&file_size=${fileSizeFormat(data.file_size) || '--'}&split_settings=${data.split_settings.join(
          ' / '
        )}&create_time=${data.create_time || '--'}&tags=${data?.tags?.join(' / ') || '--'}`
      )
    }
  }
  const typeSelected = useRef()
  const typChangeOptions: MenuProps['items'] = [
    {
      key: '999',
      label: (
        <div className="filelib-filelist-type" onClick={() => selectChange('999')}>
          <div>{t('all')}</div>
          <div>{typeSelected.current === '999' && selectedSvg}</div>
        </div>
      )
    },
    {
      key: '1',
      label: (
        <div className="filelib-filelist-type" onClick={() => selectChange('1')}>
          <div>{t('lib.parsing')}</div>
          <div>{typeSelected.current === '1' && selectedSvg}</div>
        </div>
      )
    },
    {
      key: '2',
      label: (
        <div className="filelib-filelist-type" onClick={() => selectChange('2')}>
          <div>{t('lib.completed')}</div>
          <div>{typeSelected.current === '2' && selectedSvg}</div>
        </div>
      )
    },
    {
      key: '3',
      label: (
        <div className="filelib-filelist-type" onClick={() => selectChange('3')}>
          <div>{t('lib.parseFailed')}</div>
          <div>{typeSelected.current === '3' && selectedSvg}</div>
        </div>
      )
    }
  ]

  // 文件预览相关
  const [previewOpen, setPreviewOpen] = useState(false)
  const [previewFile, setPreviewFile] = useState<FileInfoType>()
  const handlePreview = (row: FileInfoType) => {
    console.log('handlePreview', row)
    fileLibBuriedEvent({
      page: '文件列表页面',
      event_name: '【文件名称】，进入预览页面',
      data_id: id
    })
    setPreviewFile(row)
    setPreviewOpen(true)
  }

  // 定义tableColumns
  const tableColumns: columnsProps[] = [
    {
      dataIndex: 'file_name',
      title: t('lib.fileName'),
      width: 200,
      fixed: 'left',
      render: (text, _record, _index) => (
        <div className="flexRowStart">
          <Tooltip placement="topLeft" title={text}>
            <span className="domOverflowEllip" style={{ width: '90%' }}>
              {text}
            </span>
          </Tooltip>
          <Tooltip placement="top" title="预览">
            <span className="filelib_title-preview-icon_again" onClick={() => handlePreview(_record)}>
              <svg xmlns="http://www.w3.org/2000/svg" width="11" height="12" viewBox="0 0 11 12" fill="none">
                <path
                  d="M9.57084 5.14251L2.5145 0.908697C1.84797 0.508783 1 0.988896 1 1.76619V10.2338C1 11.0111 1.84797 11.4912 2.5145 11.0913L9.57085 6.85749C10.2182 6.46909 10.2182 5.53091 9.57084 5.14251Z"
                  stroke="#131921"
                  strokeWidth="1.5"
                  strokeLinejoin="round"
                />
              </svg>
            </span>
          </Tooltip>
        </div>
      ),
      ellipsis: {
        showTitle: false
      },
      className: 'filelib_name_column pr-[28px]'
    },

    // {
    //   dataIndex: 'format',
    //   title: t('lib.tag'),
    //   width: 180,
    //   render: (_text, record, _index) => {
    //     const tagList = record.tags
    //     if (tagList?.length > 0) {
    //       return (
    //         <Tooltip placement="topLeft" title={record.tags.join(' / ')}>
    //           <span className="domOverflowEllip tags_files">{tagList.join(' / ')}</span>
    //         </Tooltip>
    //       )
    //     } else {
    //       return '/'
    //     }
    //   }
    // },
    {
      dataIndex: 'status',
      title: (
        <Dropdown
          menu={{ items: typChangeOptions, selectable: true, defaultSelectedKeys: ['999'] }}
          overlayClassName="filelib-filelist-type-dropdown"
          placement="bottom"
        >
          <div className="fon flex h-[100%] w-[100%] items-center gap-[4px]">
            {t('lib.status')}
            <div className="filelib-filelist-type-icon" style={{ color: typeSelected.current && '#1968ff' }}>
              {typeSvg}
            </div>
          </div>
        </Dropdown>
      ),
      width: 160,
      render: (text, _record, _index) => {
        return text === 3 ? (
          <div className="flex items-center">
            <svg
              style={{ marginRight: '4px' }}
              width="16"
              height="16"
              viewBox="0 0 16 16"
              fill="none"
              xmlns="http://www.w3.org/2000/svg"
            >
              <circle cx="8" cy="8" r="7" fill="#FA514B" />
              <path
                d="M5.87891 5.87891L10.1215 10.1215"
                stroke="white"
                strokeWidth="1.5"
                strokeLinecap="round"
                strokeLinejoin="round"
              />
              <path
                d="M5.87891 10.1211L10.1215 5.87845"
                stroke="white"
                strokeWidth="1.5"
                strokeLinecap="round"
                strokeLinejoin="round"
              />
            </svg>

            <Tooltip placement="topLeft" title={_record.remark}>
              <span className="text-red-500">{t('lib.parseFailed')}</span>
            </Tooltip>
            <div style={{ color: '#062FF8', padding: '0 16px', boxSizing: 'border-box' }}>
              <RotateCw className="cursonCase" size={16} onClick={() => handleRetry([_record])} />
            </div>
          </div>
        ) : (
          <div className="flexRowStart">
            {text === 1 ? (
              <svg
                style={{ marginRight: '4px' }}
                width="16"
                height="16"
                viewBox="0 0 16 16"
                fill="none"
                xmlns="http://www.w3.org/2000/svg"
              >
                <circle cx="8" cy="8" r="7" fill="#FF8800" />
                <path d="M8 5L8 8H10.5" stroke="white" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
              </svg>
            ) : (
              <svg
                style={{ marginRight: '4px' }}
                width="16"
                height="16"
                viewBox="0 0 16 16"
                fill="none"
                xmlns="http://www.w3.org/2000/svg"
              >
                <circle cx="8" cy="8" r="7" fill="#38D0AF" />
                <path
                  d="M10.9673 6.81055L7.8108 9.96703L6.00001 8.15624"
                  stroke="white"
                  strokeWidth="1.5"
                  strokeLinecap="round"
                  strokeLinejoin="round"
                />
              </svg>
            )}

            <span className={text === 3 ? 'text-red-500' : ''}>
              {[t('lib.parseFailed'), t('lib.parsing'), t('lib.completed'), t('lib.parseFailed')][text]}
            </span>
          </div>
        )
      }
    },
    {
      dataIndex: 'format',
      title: t('lib.format'),
      width: 80,
      render: (_text, _record, _index) => {
        return _record.file_name ? _record.file_name.slice(_record.file_name.lastIndexOf('.') + 1) : _record.file_name
      }
    },
    {
      dataIndex: 'file_size',
      title: t('lib.size'),
      width: 100,
      render: (text, _record, _index) => fileSizeFormat(text)
    },
    {
      dataIndex: 'split_settings',
      title: t('lib.segmentation'),
      width: 240,
      render: (_text, record, _index) => {
        return record.split_settings ? (
          <Tooltip placement="topLeft" title={record.split_settings.join(' / ') || ''}>
            <div className="flexRowStart">
              <span className="segmentation_shard domOverflowEllip">
                {record?.split_settings?.length > 0 ? record.split_settings.join(' / ') : '/'}
              </span>
            </div>
          </Tooltip>
        ) : (
          '/'
        )
      }
    },
    {
      dataIndex: 'update_time',
      title: t('lib.uploadTime'),
      width: 180,
      render: (text, _record, _index) => text?.replace('T', ' ')
    },
    {
      dataIndex: 'operation',
      title: t('operations'),
      fixed: 'right',
      width: 185,
      render: (_text, record, _index) => (
        <div className="ml-[-16px] bg-inherit">
          {/* <span
            onClick={async () => {
              if (!hasFuncPermission([Func.knowledge.tags])) {
                return
              }
              if (record.status != 2) {
                return
              }
              if (tagLoading) {
                showMessage({
                  content: '请等待上一个管理标签任务结束',
                  type: 'warning'
                })
                return
              }
              setTagLoadingNum(_index)
              setTagLoading(true)
              setfile_id(record.id)
              fileLibBuriedEvent({
                page: '文件列表页面',
                event_name: '【管理标签】按钮',
                data_id: id
              })
              try {
                const list: any = await tagsCreate(record.id)
                if (list?.length > 0) {
                  const TemArr = []
                  if (record?.tags?.length > 0) {
                    record.tags.forEach(tag => {
                      TemArr.push({ label: tag, value: tag, hid: 1 })
                    })
                  }
                  setoptions([...list, ...TemArr])
                  setoptionsValues(record.tags || [])
                  setTagShow(true)
                }
              } catch (error) {
                console.log(error)

                setTagLoading(false)
              }
            }}
            className={
              record.status !== 2
                ? 'tableSettingNameNot ml-[16px] px-0 text-[#ccc]'
                : 'tableSettingName ml-[16px] px-0 text-[#062FF8]'
            }
          >
            {tagLoading && tagLoadingNum === _index ? (
              <>
                <Spin size="small" />
                生成中
              </>
            ) : (
              <>
                {t('lib.tagSetting')}
                {t('lib.tag')}
              </>
            )}
          </span> */}

          <span
            onClick={() => linkToDetail(record)}
            className={
              record.status !== 2
                ? 'tableSettingNameNot ml-[16px] px-0 text-[#ccc]'
                : 'tableSettingName ml-[16px] px-0 text-[#062FF8]'
            }
          >
            {t('lib.details')}
          </span>
          <span
            onClick={() => handleDelete(record.id)}
            className="tableSettingName ml-[16px] px-0 text-[#FA514B] text-red-500"
          >
            {t('delete')}
          </span>
          {/* 为了实现右侧fix时border-radius额外增加的遮罩层 */}
          <div className="common-table-right-fixed-layer2">{''}</div>
          <div className="common-table-right-fixed-layer3">{''}</div>
        </div>
      )
    }
  ]
  const [tagLoading, setTagLoading] = useState(false)
  const [tagLoadingNum, setTagLoadingNum] = useState(0)

  // table的分页、排序、筛选变化时触发
  const handleTableChange = (values: any) => {
    console.log('values', values)
  }

  const tagsCreate = async file_id => {
    const obj = {
      file_id,
      knowledge_name: '',
      knowledge_description: ''
    }
    return autoTags(obj).then((tags: any) => {
      const list = []
      if (tags.length > 0) {
        tags.forEach(tag => {
          list.push({
            label: tag,
            value: tag
          })
        })
      }
      setTagLoadingNum(0)
      setTagLoading(false)
      return list
    })
  }
  const [options, setoptions] = useState([])
  const [optionsValues, setoptionsValues] = useState([])
  const infoTem = {
    name: '文件信息',
    foutName: '描述',
    case: '',
    list: []
  }
  const [info, setInfo] = useState(infoTem)
  const [file_id, setfile_id] = useState('') as any
  const tagsSubmit = (checkedValues, checkedLabel) => {
    const obj = {
      tags: checkedLabel,
      file_id
    }
    setTaglabels(obj)
      .then(res => {
        fileLibBuriedEvent({
          page: '管理标签弹窗',
          event_name: '【确定】按钮',
          data_id: id,
          detail: JSON.stringify({ 数量: checkedLabel.length, 结果: '成功' })
        })
        reload()
        setTagShow(false)
      })
      .catch(err => {
        console.log(err)
        fileLibBuriedEvent({
          page: '管理标签弹窗',
          event_name: '【确定】按钮',
          data_id: id,
          detail: JSON.stringify({ 数量: checkedLabel.length, 结果: '失败' })
        })
      })
  }
  const againOptions = async () => {
    fileLibBuriedEvent({
      page: '管理标签弹窗',
      event_name: '【重新生成】按钮',
      data_id: id
    })
    const list = await tagsCreate(file_id)
    if (list?.length > 0) {
      setoptions([...list, ...options])
    }
  }

  /**
   * 高度每次基础信息展开和收起的时候手动计算
   */
  const [baseHeight, setBaseHeight] = useState(136)
  const handleHeightChange = h => {
    setBaseHeight(h)
  }

  return (
    <div className="relative h-[calc(100vh-56px)] w-full min-w-[600px] overflow-hidden rounded-[6px] bg-[#f5f7fb]">
      <div className="filelib-container rounded-[6px]" style={{ background: '#F5F7FB' }}>
        {/* head */}
        <div className="flex items-center justify-between">
          <div className="flex items-center">
            <ShadTooltip content="back" side="top">
              <button
                className="extra-side-bar-buttons w-[36px]"
                onClick={() => {
                  navigate('/filelib')
                }}
              >
                <Link to="/filelib">
                  <ArrowLeft className="side-bar-button-size" />
                </Link>
              </button>
            </ShadTooltip>
            <span className="px-4 text-sm font-black text-gray-700">{title}</span>
          </div>
        </div>
        {/* info */}
        <div className="py-[16px]">
          <InfoHead info={info} handleHeightChange={handleHeightChange}></InfoHead>
        </div>
        <div className="rounded-[8px] bg-[#fff] px-[16px]">
          {/* sele-head */}
          <div className="flexRow flexRowJustBet py-[16px]" style={{ boxSizing: 'border-box' }}>
            <div className="flexRow">
              <span className="filelib_sele_name">文件列表</span>
              <InputAntDef searchFun={e => search(e.target.value)} placeholder={t('lib.fileName')}></InputAntDef>
            </div>
            <div className="flex items-center gap-4">
              <ThemeBtn
                className="migu-font-600 h-[36px] w-[92px]"
                onClick={() => {
                  fileLibBuriedEvent({
                    page: '文件列表页面',
                    event_name: '【上传】按钮',
                    data_id: id
                  })
                  if (!hasFuncPermission([Func.knowledge.fileUpload])) {
                    return
                  }
                  setOpen(true)
                }}
              >
                {t('code.uploadFile')}
              </ThemeBtn>
            </div>
          </div>
          {/* table */}
          {loading && !isPolling && (
            <div
              className="absolute left-0 z-10 flex w-full items-center justify-center bg-[rgba(255,255,255,0.6)] dark:bg-blur-shared"
              style={{
                top: `${baseHeight + 160}px`,
                height: `calc(100vh - ${baseHeight + 388}px)`,
                maxHeight: `calc(100vh - ${baseHeight + 388}px)`
              }}
            >
              <span className="loading loading-infinity loading-lg"></span>
            </div>
          )}
          <div
            className={`tablePaddRig_files caseOverFlowY overflow-y-auto rounded-[6px]`}
            style={{
              height: `calc(100vh - ${baseHeight + 264}px)`,
              maxHeight: `calc(100vh - ${baseHeight + 264}px)`
            }}
          >
            <TableGrid
              tableInfo={{
                tableData: datalist,
                tableColumns,
                getUniqueKey, // 唯一id
                // tableIsLoading: loading,
                getTableChangeValues: handleTableChange, // 获取table事件
                scrollHeight: `calc(100vh - ${baseHeight + 368}px)`,
                scrollWidth: 800
              }}
              emptyComponent={
                !loading && !datalist?.length ? (
                  <ListEmptyNone style={{ height: `calc(100vh - ${baseHeight + 388}px)`, margin: 0 }} />
                ) : (
                  <div
                    style={{ height: `calc(100vh - ${baseHeight + 388}px)`, background: '#ffffff', margin: 0 }}
                  ></div>
                )
              }
            />
          </div>
        </div>

        {/* footer */}
        <FouterPage
          style={{ background: '#FFFFFF' }}
          className="filelib-bottom-box filelib-gray-text rounded-[6px]"
          page={page}
          pageSize={pageSize}
          total={total}
          setPage={newPage => setPage(newPage)}
        ></FouterPage>
      </div>
      {/* upload modal */}
      {open ? (
        <UploadModal
          id={id}
          accept={appConfig.libAccepts}
          open={open}
          setOpen={handleOpen}
          onResult={handleUploadResult}
          MaxFileSize={4}
          filelibType={'fileLibPage'}
        ></UploadModal>
      ) : null}
      {/* tag 标签 */}
      {tagShow ? (
        <TagDialog
          defoptions={options}
          optionsValues={optionsValues}
          cancel={e => {
            fileLibBuriedEvent({
              page: '管理标签弹窗',
              event_name: '【取消】按钮',
              data_id: id
            })
            setTagShow(false)
          }}
          submit={(checkedValues, checkedLabel) => {
            tagsSubmit(checkedValues, checkedLabel)
          }}
          again={() => {
            againOptions()
          }}
          updata={(options, checkedValues) => {
            setoptions(options)
            setoptionsValues(checkedValues)
          }}
        ></TagDialog>
      ) : null}
      {/* 重复文件提醒 */}
      <dialog className={`modal ${!errorFiles.length && repeatFiles.length && 'modal-open'}`}>
        <div className="modal-box w-[560px] bg-[#fff] shadow-lg dark:bg-background">
          <h3 className="relative text-lg font-bold">
            {t('lib.modalTitle')}
            <X
              className="absolute right-0 top-0 cursor-pointer text-gray-400"
              size={20}
              onClick={() => {
                reload()
                setRepeatFiles([])
              }}
            ></X>
          </h3>
          <p className="py-4">{t('lib.modalMessage')}</p>
          <ul className="max-h-[400px] overflow-y-auto">
            {repeatFiles.map(el => (
              <li key={el.id} className="py-2 text-red-500">
                {el.remark}
              </li>
            ))}
          </ul>
          <div className="flexRow" style={{ marginTop: '1.5rem' }}>
            <Button
              className="h-8"
              onClick={() => {
                reload()
                setRepeatFiles([])
              }}
            >
              {t('lib.keepOriginal')}
            </Button>
            <Button
              type="primary"
              style={{ marginLeft: '10px' }}
              className="h-8"
              disabled={retryLoad}
              onClick={() => handleRetry(repeatFiles)}
            >
              {retryLoad && <span className="loading loading-spinner loading-xs"></span>}
              {t('lib.override')}
            </Button>
          </div>
        </div>
      </dialog>
      {/* 文件预览 */}
      {previewOpen && <PreviewPage open={previewOpen} fileInfo={previewFile} setOpen={setPreviewOpen} />}
      {errorFiles.length ? (
        <Modal
          title="百应云空间文件上传失败提示"
          width={600}
          onCancel={() => setErrorFiles([])}
          open={true}
          footer={
            <Button type="primary" onClick={() => setErrorFiles([])}>
              确认
            </Button>
          }
        >
          <p className="py-4">以下百应云空间文件上传失败，请尝试在百应云空间下载文件后通过本地上传</p>
          <ul className="max-h-[400px] overflow-y-auto">
            {errorFiles.map((el, index) => (
              <li key={index} className="py-2 text-red-500">
                {el.remark}
              </li>
            ))}
          </ul>
        </Modal>
      ) : (
        ''
      )}
    </div>
  )
}

const selectedSvg = (
  <svg xmlns="http://www.w3.org/2000/svg" width="14" height="14" viewBox="0 0 14 14" fill="none">
    <path d="M3 6L6 9L11 4" stroke="#1968FF" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" />
  </svg>
)

const typeSvg = (
  <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 16 16" fill="none">
    <path
      d="M13.249 2.83448L9.62835 6.85739C9.54572 6.9492 9.5 7.06835 9.5 7.19187V13.0657C9.5 13.4651 9.05493 13.7033 8.72265 13.4818L6.72265 12.1484C6.58355 12.0557 6.5 11.8996 6.5 11.7324V7.19187C6.5 7.06835 6.45428 6.9492 6.37165 6.85739L2.75103 2.83448C2.46145 2.51272 2.6898 2 3.12268 2H12.8773C13.3102 2 13.5386 2.51272 13.249 2.83448Z"
      stroke="currentColor"
      strokeWidth="1.5"
      strokeLinecap="round"
      strokeLinejoin="round"
    />
  </svg>
)
